﻿using HtmlAgilityPack;
using OF.Utility;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using YouWei.Utility;

namespace YouWei.Op.Common
{
    public class CommentDetailProcess
    {
        string ComplateLocalPath = ConfigHelper.GetAppSettingValue("CommentImageTmpPath"); //原图地址
        string CommentImageLocalPath = ConfigHelper.GetAppSettingValue("CommentImageLocalPath");//剪切去水印后地址
        string CommentImageLocalPathCompress = ConfigHelper.GetAppSettingValue("CommentImageListPath");//缩略图地址
        string CommentImageServerUrl = ConfigHelper.GetAppSettingValue("CommentImageServerUrl");

        public string ProcessDetail(string Detail)
        {
            if (!string.IsNullOrWhiteSpace(Detail))
            {
                Detail = RemoveHTMLTags(Detail);
                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(Detail);
                for (int i = 0; i < htmlDoc.DocumentNode.ChildNodes.Count; i++)
                {
                    var node = htmlDoc.DocumentNode.ChildNodes[i];
                    bool remove = EachProcess(node);
                    if (remove)
                    {
                        --i;
                    }
                }
                Detail = htmlDoc.DocumentNode.InnerHtml;
            }
            return Detail;
        }

        protected bool EachProcess(HtmlNode node)
        {
            try
            {
                node.RemoveClass();
                if (node.Name.Equals("img", StringComparison.OrdinalIgnoreCase))
                {
                    var srcDom = node.Attributes["src"];
                    if (srcDom == null)
                        srcDom = node.Attributes["data-src"];
                    if (srcDom == null)
                    {
                        node.Remove();
                        return true;
                    }
                    else
                    {
                        ProcessImage(node);
                        return false;
                    }

                }
                else if (node.Name.Equals("strong", StringComparison.OrdinalIgnoreCase))
                {
                    var newStrong = HtmlNode.CreateNode(node.InnerText);
                    node.ParentNode.ReplaceChild(newStrong, node);
                    node.Remove();
                    return false;
                }
                if (node.HasAttributes)
                {
                    node.Attributes.RemoveAll();
                }

                if (string.IsNullOrWhiteSpace(node.InnerText))
                {
                    if (HasImage(node))
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            bool remove = EachProcess(node.ChildNodes[i]);
                            if (remove)
                            {
                                --i;
                            }
                        }
                    }
                    else
                    {
                        node.Remove();
                        return true;
                    }
                }
                else
                {
                    if (node.HasChildNodes)
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            bool remove = EachProcess(node.ChildNodes[i]);
                            if (remove)
                            {
                                --i;
                            }
                        }
                        if (string.IsNullOrWhiteSpace(node.InnerText))
                        {
                            if (HasImage(node))
                            {

                            }
                            else
                            {
                                node.Remove();
                                return true;
                            }
                        }
                    }
                    else
                    {
                        string text = FilterChar(node.InnerText);
                        var newStrong = HtmlNode.CreateNode(text);
                        node.ParentNode.ReplaceChild(newStrong, node);
                        node.Remove();

                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            return false;
        }

        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private string FilterChar(string input)
        {
            string[] bds = new string[] { "，", ",", "。", ".", "；", ";", "-", "_", "、", "!", "！", "“", "”", "\"", "‘", "'", ":", "：" };

            Regex r = new Regex("^[0-9]{1,}$"); //正则表达式 表示数字的范围 ^符号是开始，$是关闭
            StringBuilder sb = new StringBuilder();
            foreach (var item in input)
            {
                if (item >= 0x4e00 && item <= 0x9fbb)//汉字范围
                {
                    sb.Append(item);
                }
                else if (Regex.IsMatch(item.ToString(), @"[A-Za-z0-9]"))  //字母
                {
                    sb.Append(item);
                }
                else
                {
                    if (bds.Contains(item.ToString()))
                    {  //标点服务
                        sb.Append(item);
                    }
                }

            }
            return sb.ToString();
        }

        /// <summary>
        /// 替换特殊标签
        /// </summary>
        /// <param name="htmlStream"></param>
        /// <returns></returns>
        public string RemoveHTMLTags(string htmlStream)
        {
            //替换空格:&nbsp;|&amp;|&shy;|&#160;|&#173;
            htmlStream = Regex.Replace(htmlStream, "&nbsp;|nbsp;|&amp;|&shy;|&#160;|&#173;|&bull;|&lt;|&gt;|quot;", "", RegexOptions.IgnoreCase);
            htmlStream = Regex.Replace(htmlStream, "&nbsp；|nbsp；|&amp；|&shy；|&#160；|&#173；|&bull；|&lt；|&gt；|quot；", "", RegexOptions.IgnoreCase);
            return htmlStream.Trim();
        }

        /// <summary>
        /// 判断是否存在图片
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        protected bool HasImage(HtmlNode node)
        {
            var imgs = node.SelectNodes(".//img");
            if (imgs != null && imgs.Count > 0)
            {
                return true;
            }
            return false;

        }

        protected bool ProcessImage(HtmlNode node)
        {
            var srcDom = node.Attributes["src"];
            if (srcDom == null)
                srcDom = node.Attributes["data-src"];
            if (srcDom == null)
            {
                node.Remove();
                return true;
            }
            string src = srcDom.Value;
            //如果链接不包含CommentImageServerUrl值，则为外链图片，下载到本地再替换链接; 否则则为抓取或本地上传图片，不做处理
            if (src.IndexOf(CommentImageServerUrl) < 0)
            {
                if (!string.IsNullOrWhiteSpace(src))
                {
                    string dir = Path.GetDirectoryName(ComplateLocalPath);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    var fileName = "/" + Guid.NewGuid().ToString("N") + ".jpg";
                    var savePath = ComplateLocalPath + fileName;

                    using (var img = ImageHelper.UrlToImage(src))
                    {
                        using (Bitmap tempImage = new Bitmap(img))
                        {
                            tempImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }

                        //裁剪高度0.9水印
                        int height = Convert.ToInt32(img.Height * 0.9);

                        PictureUtility.CaptureImage(savePath, 0, 0, CommentImageLocalPath + fileName, img.Width, height);

                        //缩略图
                        PictureUtility.ComPressJPEG(Image.FromFile(CommentImageLocalPath + fileName), img.Width, img.Height)
                                      .Save(CommentImageLocalPathCompress + fileName);
                    }

                    node.SetAttributeValue("src", CommentImageServerUrl + fileName);
                }
                node.SetAttributeValue("style", "");
                node.SetAttributeValue("data-src", "");
            }
            return false;
        }
    }
}